/**
 * Copyright (c) 2008, Keisuke Inoue, Syracuse Unviersity
 * All rights reserved.
 *
 */
package edu.syr.iis.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.syr.iis.web.model.User;
import edu.syr.iis.web.model.UserManager;
import edu.syr.iis.web.util.SecurityManager;

/**
 * @author kinoue
 *
 */
public class SignInController extends SimpleFormController
{
	private UserManager userManager;
	private SecurityManager securityManager; 

	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
	{
		return new User();
	}   

	@Override
	public ModelAndView showForm(
			HttpServletRequest request,
			HttpServletResponse response,
			BindException errors) throws Exception
			{

		if (securityManager.getUser(request) != null)
			return new ModelAndView(getSuccessView());

		return super.showForm(request, response, errors);

			}


	@Override
	protected ModelAndView onSubmit(
			HttpServletRequest request,
			HttpServletResponse response,
			Object command,
			BindException errors)
	{
		return new ModelAndView(getSuccessView());
	}
	
	
	@Override
	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception 
			{
	
		User formUser = (User) command;
		
		System.out.println("Entering onBindAndValidate with user name:" + formUser.getUserName() );
		User user = userManager.checkUser(formUser.getUserName(), formUser.getPassword());

		if (user != null)
		  System.out.println("User: " + user.getUserName());
		
		if (user == null) 
		{
			System.out.println("Throwing an error.");
			errors.reject("invalid.login", "Wrong username/password!");
		}
		else
			securityManager.singIn(request, user);
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public SecurityManager getSecurityManager() {
		return securityManager;
	}

	public void setSecurityManager(SecurityManager securityManager) {
		this.securityManager = securityManager;
	}

	/*
	public String getUserView() {
		return userView;
	}

	public void setUserView(String userView) {
		this.userView = userView;
	}

	public String getAdminView() {
		return adminView;
	}

	public void setAdminView(String adminView) {
		this.adminView = adminView;
	}
*/

}
